import { useEffect, useState } from "react";
import { getTableApi, getToken } from "../utils/client";
import { Table } from "antd";
import type { ColumnsType } from 'antd/es/table';


export interface TableDescProps {
    curClientId: string;
    curDatabase: string;
    curTable: string;
}

interface DescInfo {
    name: string;
    dataType: string;
    defaultValue: string;
    nullAble: string;
}

function TableDesc(props: TableDescProps) {
    const [descList, setDescList] = useState<DescInfo[]>([]);

    const loadTableDesc = async () => {
        setDescList([]);
        const client = getTableApi();
        const res = await client.tableRawQueryPost({
            tableRawQueryPostRequest: {
                id: props.curClientId,
                token: getToken(),
                db: props.curDatabase,
                sql: `SELECT table_name, column_name, data_type, column_default, is_nullable FROM information_schema.columns WHERE table_name = '${props.curTable}'`,
            },
        });

        if (res.columns !== undefined && res.values !== undefined) {
            const tmpList = [] as DescInfo[];
            for (const row of res.values) {
                const info: DescInfo = {
                    name: "",
                    dataType: "",
                    defaultValue: "",
                    nullAble: "",
                };
                row.forEach((value, index) => {
                    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                    const colName = res.columns![index].name!.toLowerCase();
                    if (colName == "column_name") {
                        info.name = value ?? "";
                    } else if (colName == "data_type") {
                        info.dataType = value ?? "";
                    } else if (colName == "column_default") {
                        info.defaultValue = value ?? "";
                    } else if (colName == "is_nullable") {
                        info.nullAble = value ?? "";
                    } 
                });
                tmpList.push(info);
            }
            setDescList(tmpList);
        }
    };

    const columns: ColumnsType<DescInfo> = [
        {
            title: "字段",
            dataIndex: "name",
        },
        {
            title: "类型",
            dataIndex: "dataType",
        },
        {
            title: "可否为null",
            dataIndex: "nullAble",
        },
        {
            title: "默认值",
            dataIndex: "defaultValue",
        },
    ];

    useEffect(() => {
        if (props.curClientId !== "" && props.curDatabase !== "" && props.curTable !== "") {
            loadTableDesc();
        } else {
            setDescList([]);
        }
    }, [props.curClientId, props.curDatabase, props.curTable]);

    return (
        <Table rowKey="name" columns={columns} dataSource={descList} pagination={false} />
    );
}

export default TableDesc;